package mysql

import (
	"bluebell/models"
	"github.com/jmoiron/sqlx"
	"strings"
)

func CreatePost(param *models.Post) (err error) {
	sqlStr := `insert into post(id, author_id, title, content, community_id) value (?,?,?,?,?)`
	_, err = db.Exec(sqlStr, param.ID, param.AuthorID, param.Title, param.Content, param.CommunityID)
	return
}

func GenPostById(id int64) (post *models.Post, err error) {
	sqlStr := `select id , author_id, community_id, title, content, create_time from post where id=? and status=1`
	post = new(models.Post)
	err = db.Get(post, sqlStr, id)
	return
}

func GenPostList(page, limit int64) (posts []*models.Post, err error) {
	sqlStr := `
		select id, title, content, author_id, community_id, create_time
		from post
		ORDER BY create_time DESC
    limit ?,?
	`
	err = db.Select(&posts, sqlStr, (page-1)*limit, limit)
	return
}

func GenPostListByIds(ids []string) (posts []*models.Post, err error) {
	sqlStr := `select id, title, content, author_id, community_id, create_time
		from post
		where id in (?)
		order by FIND_IN_SET(id, ?)
	`
	var (
		query string
		args  []interface{}
	)
	query, args, err = sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	if err != nil {
		return nil, err
	}
	query = db.Rebind(query)
	err = db.Select(&posts, query, args...)
	return
}
